from django.shortcuts import render
from rest_framework import status
from rest_framework.generics import CreateAPIView
from rest_framework.views import APIView
from rest_framework.response import Response
from apps.users.models import UserModel
from apps.users import seriali
from fuguang.utils.ronglianyunapi import send_message
import random
from django_redis import get_redis_connection
from django.conf import settings


# Create your views here.
# 测试视图，用于创建用户
class CreateUserViews(APIView):
    def get(self,request):

        # UserModel.objects.create()  表示往数据单纯得插入一条数据
        UserModel.objects.create_user(username='root',email='123@123.com',password='123',mobile="18300000000")
        # user = UserModel.objects.create(username='shanshan',email='123@123.com',password='123',mobile="18000000001")
        # user.set_password('123')
        return Response({"message":"用户创建成功"})


# 选用什么视图？？？？？
# APIView ：
# CreateApiView  :序列化器中实现业务逻辑判断
# 序列化器：序列化：orm得模型对象转成json格式得字符串，，，和反序列化将json格式得字符串转成模型对象
# 数据校验
# 保存数据
# update
class RegisterViews(CreateAPIView):
    queryset = UserModel.objects.all()
    serializer_class = seriali.RegisterSerializer



# 判断手机号是否重复
class MobileApiView(APIView):
    def get(self,request,mobile):
        try:
            UserModel.objects.get(mobile__exact=mobile)
            return Response({"message":"手机号已存在"},status=status.HTTP_400_BAD_REQUEST)
        except UserModel.DoesNotExist:
            return Response({"message":"手机号可以注册"},status=status.HTTP_200_OK)

class SmsApiView(APIView):
    def get(self,request,mobile):

        # -------------------redis:短信验证码------------------
        # 获取redis的连接
        redis = get_redis_connection('sms_code')
        # 获取redis中,手机号验证码60秒发送间隔,是否过期
        res_interval = redis.ttl(f"interval_{mobile}")
        # 如果等于-2  表示数据过期
        if res_interval != -2:
            return Response({'message':'验证码还在有效期内,请勿频繁发送验证码'},status=status.HTTP_400_BAD_REQUEST)





        ronglianyun = settings.RONGLIANYUN
        # 获取过期时间
        sms_expire = ronglianyun.get('sms_expire')
        tid = ronglianyun.get('reg_tid')
        sms_interval = ronglianyun.get('sms_interval')

        # mobile = '18201275696'
        code = f'{random.randint(0,9999):04d}'
        interval = sms_interval/60
        # 基本发送短信完成
        # 如何存储验证码
        datas = (code, interval)
        # tid = "1"
        # mobile = '18201275696'
        # datas = ('9823', '2')
        # res = send_message(tid,mobile,datas)
        print(code)
        from mycelery.sms.tasks import send_sms
        # 异步任务实现发送短信
        # send_sms.delay(tid,mobile,datas)



        # -------------------redis:短信验证码------------------
        # redis写入验证码,     sms_18201275699
        # reids  提供了  简单事务
        # 开启管道,优化redis写入, 执行的,一次性将所有指令发送给redis
        # 开启事务

        pipe = redis.pipeline()
        pipe.multi()  # 开启redis事务,保证所有命令 正确执行
        redis.setex(f"sms_{mobile}", sms_expire, code)
        # 短信发送的间隔时间
        redis.setex(f"interval_{mobile}", sms_interval, '-')
        # 提交事务,把暂存在pipeline对象中多条命令,一次性提交给reids
        pipe.execute()
        # -------------------redis:短信验证码------------------

        # if res:
        return Response({'message':'短信发送成功...'},status=status.HTTP_200_OK)
        # else:
        #     return Response({'message':'短信发送失败...'},status=status.HTTP_400_BAD_REQUEST)










